<template>
  <div class="page">
    <h2>示例04 - 合计行</h2>
    <vue-tabulation
      ref="grid"
      :dataSource="dataSource"
      :columns="columns"
      :height="500"
      :showSummary="showSummary"
      :summaryMethod="summaryMethod"
    ></vue-tabulation>
    <hr />
    <button @click="showSummary = !showSummary">toggle summary</button>
  </div>
</template>

<script>
export default {
  name: 'demo-summary',
  data() {
    return {
      dataSource: this.$mock.dataSource(100),
      columns: this.$mock.columns().map(item => {
        if (item.prop === 'age') {
          item.align = 'center'
        }
        return item
      }),
      showSummary: true,
    }
  },
  methods: {
    summaryMethod({ columns, data }) {
      const isAllNumber = arr => {
        return arr.every(item => typeof item !== 'boolean' && !isNaN(Number(item)))
      }
      return columns.map((item, index) => {
        let values = data.map(itemData => itemData[item.prop])
        if (index === 0) {
          return '总共'
        } else if (isAllNumber(values)) {
          let sum = values.reduce((prev, curr) => {
            return prev + Number(curr)
          }, 0)
          if (item.prop === 'age') {
            sum = sum + '岁'
          }
          return sum
        } else {
          return ''
        }
      })
    },
  },
}
</script>
